<script setup>
import { onMounted, nextTick, ref, reactive, watch, toRefs, watchEffect, isRef } from 'vue'
import { useDraggable } from '@vueuse/core'
import * as echarts from 'echarts'
import { getWaveRange, tempDate, getAfterDate, formatDate } from '../forecast/fore'
import Config from './mapConfig'
import { layerData } from '../mapInfoObj/initMap'
const props = defineProps({
  location: {
    type: Object,
    default: {
      lng: 0,
      lat: 0,
      x: 0,
      y: 0
    }
  }
})
const { location } = toRefs(props)
const emit = defineEmits(['closeInfo', 'refreshPoint', 'showChart'])
const closeInfo = () => {
  emit('closeInfo')
}

onMounted(() => {
  x.value = location.value.x
  y.value = location.value.y
})
const el = ref(null)

const { x, y, style } = useDraggable(el, {
  initialValue: { x: 0, y: 0 },
})

let timer = null
const latlng = ref([])



watch(location, () => {
  x.value = location.value.x + 28
  y.value = location.value.y
  latlng.value[0] = location.value.lng
  latlng.value[1] = location.value.lat
})

watch([x, y], () => {
  if (timer) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    emit('refreshPoint', { x: x.value - 28, y: y.value })
  }, 100);
})

const drawer = ref(false)

const showChart = () => {
  console.log(Config);
  emit('showChart')
  drawer.value = true
  nextTick(() => {
    initChart()
  })
},
  handleClose = () => {
    drawer.value = false
    chart.dispose()
  }

const chartRef = ref(null)
let chart = null

let allData = []
let currentDataList = ref({})
let allP = []

const handleGetWaveRange = (data) => {
  let startDateTime = tempDate.value + ' 00:00'
  // 三天内
  let endDateTime = formatDate(getAfterDate(tempDate.value, 1), 'YYYY-MM-DD') + ' 23:59'
  // let endDateTime = tempDate.value + ' 23:59'
  // 第二天的0点
  // let endDateTime = tempDate.value + ' 23:59'
  let formData = new FormData()
  formData.append('startDateTime', startDateTime)
  formData.append('endDateTime', endDateTime)
  formData.append('featureType', data.type.type)
  formData.append('latitude', data.lat)
  formData.append('longitude', data.lng);

  allP.push(getWaveRange(formData))
  return
  getWaveRange(formData).then(res => {
    currentDataList.value[data.type.type] = res.data.data[data.type.result]
    return


    if (data.type == 'wave') {
      option.series[0].data = res.data.data.waveDataList.map(item => {
        return {
          value: item[0],
          // symbolRotate: item[1]增加180度，超过360度取余
          symbolRotate: item[1] + 180 > 360 ? item[1] + 180 - 360 : item[1] + 180
        }
      })
      chart.setOption(option)
    } else if (data.type == 'tide') {
      // console.log(res.data.data);
      // 不显示symbol
      option.series[0].symbol = 'none'
      option.series[0].name = '潮高'
      option.tooltip = {
        trigger: 'axis',
        formatter: function (params) {
          params = params[0]
          return '潮高: ' + (params.data.value * 100).toFixed(2) + 'cm'
        },
      }
      option.series[0].data = res.data.data.tideDataList
        .map(item => {
          return {
            value: item,
          }
        })
      chart.setOption(option)
    } else if (data.type == 'wind') {
      currentDataList.value = res.data.data.windDataList
      option.series[0].data = res.data.data.windDataList.map(item => {
        return {
          value: item[0],
          // symbolRotate: item[1]增加180度，超过360度取余
          symbolRotate: item[1]
        }
      })
      option.series[0].name = '风速'
      // option.legend.data = ['风速']
      option.tooltip = {
        trigger: 'axis',
        formatter: function (params) {
          params = params[0]
          return '风速: ' + params.data.value + 'm/s' + '<br/>' + '风向: ' + params.data.symbolRotate + '°'
        },
      }
      chart.setOption(option)
    }
    // console.log(res);
    // option.series[0].data = res.data.data
  })
}
let option = {
  tooltip: {
    trigger: 'axis',
  },
  legend: {
  },
  grid: {
    left: '4%',
    right: '5%',
    bottom: '1%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    // data: Array.from({ length: 24 }, (v, k) => k < 10 ? '0' + k : k).map(item => {
    //   return tempDate.value + ' ' + item + ':00'
    // })
    data:[]
  },
  yAxis: [
    {
      type: 'value',
      name: "风速(m/s)",
      position: 'left',
      axisLine: {
        show: true,
      },
    },
    {
      type: 'value',
      name: "潮位(cm)",
      position: 'left',
      offset: 60,
      axisLine: {
        show: true,
      },
    },
    {
      type: 'value',
      name: "浪高(m)",
      position: 'right',
      axisLine: {
        show: true,
      },
    },
    {
      type: 'value',
      name: "流速(m/s)",
      position: 'right',
      offset: 50,
      axisLine: {
        show: true,
      },
    }
  ],
  series: [
  ]
};
const initChart = () => {
  option.series = []
  allP = []
  currentDataList.value = {}
  chart = echarts.init(chartRef.value)
  let types = [
    {
      type: 'wind',
      result: 'windDataList'
    },
    {
      type: 'tide',
      result: 'tideDataList'
    },
    {
      type: 'wave',
      result: 'waveDataList'
    },
    {
      type: 'current',
      result: 'currentDataList'
    },
    {
      type: 'surge',
      result: 'surgeDataList'
    },
  ]
  types.forEach(type => {
    handleGetWaveRange({
      lat: location.value.lat,
      lng: location.value.lng,
      type: type
    })
  })
  // option.xAxis.data
  for(let i=0;i<48;i++){
    option.xAxis.data.push(formatDate(getAfterDate(tempDate.value, i / 24), 'YYYY-MM-DD HH:mm').split(' ')[0]+' '+getHour(i)+':00')
    // console.log(formatDate(getAfterDate(tempDate.value, i / 24), 'YYYY-MM-DD HH:mm').split(' ')[0]+' '+getHour(i)+':00');
  }


  Promise.all(allP).then(resArr => {
    resArr.forEach(res => {
      for (let key in res.data.data) {
        // let isZero=res.data.data[key].every(item=>{
        //   return item=0||(item[0]==0&&item[1]==0)
        // })
        if (res.data.data[key]) {
          if (key == 'windDataList' || key == 'waveDataList' || key == 'currentDataList') {
            let isZero = res.data.data[key].every(item => {
              if (!item) {
                return true
              }
              return false
            })
            if (!isZero) {
              currentDataList.value[key.split('Data')[0]] = res.data.data[key]
              // 双要素
              let yAxisIndex = 2
              if (key == 'windDataList') {
                yAxisIndex = 0
              } else if (key == 'currentDataList') {
                yAxisIndex = 3
              }
              option.series.push({
                name: getLabel(key.split('Data')[0]),
                type: 'line',
                yAxisIndex: yAxisIndex,
                data: res.data.data[key].map(item => {
                  if (key == 'currentDataList') {
                    return {
                      value: Math.sqrt(Math.pow(item[0], 2) + Math.pow(item[1], 2)).toFixed(3),
                    }
                  }
                  return {
                    value: item[0],
                    symbolRotate: item[1]
                  }
                }),
                smooth: true,
              })
            }
          } else if (key == 'tideDataList' || key == 'surgeDataList') {
            let isZero = res.data.data[key].every(item => {
              if (!item) {
                return true
              }
              return false
            })
            if (!isZero) {
              currentDataList.value[key.split('Data')[0]] = res.data.data[key].map(item => {
                return Math.round(item * 100)
              })

              // 单要素
              option.series.push({
                name: getLabel(key.split('Data')[0]),
                type: 'line',
                yAxisIndex: 1,
                data: res.data.data[key].map(item => {
                  return {
                    value: Math.round(item * 100),
                  }
                }),
                smooth: true,
              })
            }
          }
        }
      }
    })
    chart.setOption(option)
    // console.log(document.getElementsByClassName('chart_row'));
    nextTick(() => {
      let allHeight = (document.getElementsByClassName('chart_row').length - 1) * 35 + 250 + 90
      drawHeight.value = allHeight
    })
  })
}

const drawHeight = ref(600)


const getBgColor = (value, key) => {
  let color = Config.scalarColor[key][Config.scalarColor[key].length - 1].color
  let isColor = false
  Config.scalarColor[key].forEach((item, idx) => {
    if (isColor) return
    if (item.value > value) {
      if (idx == 0) {
        color = item.color
        isColor = true
        return
      }
      color = Config.scalarColor[key][idx - 1].color
      isColor = true
    }
  })
  let fontColor = 'black'
  let rgb = color.split('(')[1].split(')')[0].split(',')
  // 判断背景颜色是亮色还是暗色，来决定字体颜色
  if (rgb[0] * 0.299 + rgb[1] * 0.578 + rgb[2] * 0.114 >= 192) {
    fontColor = 'black'
  } else {
    fontColor = 'white'
  }

  return {
    bgColor: color,
    color: fontColor
  }
}


const getLabel = (key) => {
  switch (key) {
    case 'wind':
      return '风速(m/s)'
    case 'tide':
      return '潮高(cm)'
    case 'wave':
      return '浪高(m)'
    case 'current':
      return '流速(m/s)'
    case 'surge':
      return '增水'
    default:
      return ''
  }
}

const getHour = (i) => {
  let hour = i % 24
  if (hour < 10) {
    return '0' + hour
  }
  return hour
}
</script>

<template>
  <div class="LayerInfo">
    <div class="layer_content" ref="el" :style="style" style="position: fixed">
      <div class="location_info">
        <img class="location_icon" src="/img/location.png" alt="">
        <span> {{ latlng[0]?.toFixed(3) }}°E ,{{ latlng[1]?.toFixed(3) }}°N</span>
        <img class="location_close" src="@/assets/img/close.png" alt="" @click="closeInfo">
      </div>
      <div class="data_info">
        <div v-if="location.type == 'wave'">
          <div>浪高：{{ location?.value?.value }}m</div>
          <div>浪向：{{ location?.value?.angle }}°</div>
        </div>
        <div v-if="location.type == 'tide'">
          <div>潮高：{{ location?.value?.value }}cm</div>
        </div>
        <div v-if="location.type == 'surge'">
          <div>潮高：{{ location?.value?.value }}cm</div>
        </div>
        <div v-if="location.type == 'wind'">
          <div>风速：{{ location?.value?.value }}m/s</div>
          <div>风向：{{ location?.value?.angle < 180 ? location?.value?.angle + 180 : location?.value?.angle - 180 }}° </div>
          </div>
          <img id="chart_img" src="/img/chart.png" alt="" @click="showChart">
        </div>

        <div class="layer_line"></div>
        <div class="layer_point"></div>
      </div>
      <!--底部弹窗 -->
      <el-drawer v-model="drawer" direction="btt" :with-header="false" :modal="false" :size="drawHeight">
        <div class="draw_title">
          <span>经度：{{ latlng[0]?.toFixed(3) }}°E &nbsp;&nbsp;&nbsp;
            纬度：{{ latlng[1]?.toFixed(3) }}°N</span>
          <img class="location_close" src="/img/close.png" alt="" @click="handleClose">
        </div>
        <el-divider></el-divider>
        <div style="padding: 5px;">
          <el-row class="chart_row">
            <el-col :span="1">
              <div class="chart_label">
                日期
              </div>
            </el-col>
            <el-col :span="23">
              <div class="chart_content">
                <table style="width: 100%;">
                  <tr>
                    <td v-for="(,i) in 48" style="white-space: nowrap;">
                      {{ getHour(i) == '00' ? formatDate(getAfterDate(tempDate, i / 24), 'YYYY-MM-DD') : '' }}
                    </td>
                  </tr>
                </table>
              </div>
            </el-col>
          </el-row>
          <el-row class="chart_row">
            <el-col :span="1">
              <div class="chart_label">
                时刻
              </div>
            </el-col>
            <el-col :span="23">
              <div class="chart_content">
                <table style="width: 100%;">
                  <tr>
                    <td v-for="(,i) in 48">
                      {{ getHour(i) }}
                    </td>
                  </tr>
                </table>
              </div>
            </el-col>
          </el-row>
          <template v-for="(item, key) in currentDataList">
            <el-row class="chart_row" v-if="key == 'surge' || key == 'tide'">
              <el-col :span="1">
                <div class="chart_label">
                  {{ getLabel(key) }}
                </div>
              </el-col>
              <el-col :span="23">
                <div class="chart_content">
                  <table style="width: 100%;">
                    <tr>
                      <td class="td_txt"
                        :style="{ backgroundColor: getBgColor(i, key).bgColor, color: getBgColor(i, key).color }"
                        v-for="i in item">
                        {{ i }}
                      </td>
                    </tr>
                  </table>
                </div>
              </el-col>
            </el-row>
            <el-row class="chart_row" v-else-if="key == 'wind' || key == 'wave'">
              <el-col :span="1">
                <div class="chart_label">
                  {{ getLabel(key) }}
                </div>
              </el-col>
              <el-col :span="23">
                <div class="chart_content">
                  <table style="width: 100%;">
                    <tr>
                      <td class="td_txt"
                        :style="{ backgroundColor: getBgColor(i[0], key).bgColor, color: getBgColor(i, key).color }"
                        v-for="i in item">
                        {{ i[0] }}
                      </td>
                    </tr>
                  </table>
                </div>
              </el-col>
            </el-row>
            <template v-if="key == 'wind' || key == 'wave'">
              <el-row class="chart_row">
                <el-col :span="1">
                  <div class="chart_label">
                    <template v-if="key == 'wind'">风向</template>
                    <template v-else>浪向</template>
                  </div>
                </el-col>
                <el-col :span="23">
                  <div class="chart_content">
                    <table style="width: 100%">
                      <tr>
                        <td v-for="i in item">
                          <img src="/img/arrowblack.png" alt="" style="height: 20px; margin-left: 10px"
                            :style="{ transform: 'rotate(' + i[1] + 'deg)' }" />
                        </td>
                      </tr>
                    </table>
                  </div>
                </el-col>
              </el-row>
            </template>
          </template>
          <el-row class="chart_row" style="margin-top: 10px;">
            <el-col :span="1">
              <div class="chart_label">
                图表
              </div>
            </el-col>
            <el-col :span="23">
              <div class="draw_content" ref="chartRef" style="width: 100%;height: 250px;">
              </div>
            </el-col>
          </el-row>
        </div>
      </el-drawer>
    </div>
</template>

<style lang='less' scoped>
.LayerInfo {
  // position: absolute;
  z-index: 90;
  width: 300px;
  height: 150px;
  position: fixed;

  :deep(.el-drawer__body) {
    padding: 0;
    display: flex;
    flex-direction: column;
  }

  .el-divider {
    margin: 5px 0;
  }

  :deep(.el-drawer) {
    // height: 68% !important;

  }



  .draw_title {
    // background-color: antiquewhite; 
    font-family: '阿里妈妈方圆', sans-serif;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    font-weight: bold;

    img {
      position: absolute;
      right: 10px;
      width: 20px;
      height: 20px;
      // margin-left: auto;
      // margin-right: 5px;
      cursor: pointer;
    }
  }

  .chart_row {
    height: 35px;

    .chart_label {
      display: flex;
      justify-content: center;
      height: 100%;
      align-items: center;
      font-family: '阿里妈妈方圆', sans-serif;
      font-weight: 500;
    }

    .chart_content {
      display: flex;
      align-items: center;
      width: 100%;
      height: 100%;
      // justify-content: center;
      align-items: center;
      font-family: '阿里妈妈方圆', sans-serif;
      font-weight: 500;

      table {
        width: 100%;
        height: 100%;
        table-layout: fixed;

        td {
          text-align: center;
          // border: 1px solid #ccc;
        }
      }
    }
  }

  .draw_content {
    // height: 400px;
    flex: 1;
  }

  .layer_content {
    position: absolute;
    right: 0;
    top: 0;
    width: 240px;
    background-color: rgba(0, 0, 0, 0.6);
    cursor: move;
    color: white;
    font-size: 14px;
    padding: 5px;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 2px 4px 0 rgba(0, 0, 0, 0.19);

    .location_info {
      display: flex;
      // align-items: center;
      margin-bottom: 5px;
      height: 30px;
      border-bottom: 1px solid #fff;

      .location_icon {
        width: 20px;
        height: 20px;
        margin-right: 5px;
      }

      .location_close {
        width: 15px;
        height: 15px;
        margin-left: auto;
        margin-right: 5px;
        cursor: pointer;
      }
    }

    .data_info {
      margin-left: 15px;
    }

    #chart_img {
      // 右下角
      position: absolute;
      bottom: 0;
      right: 0;
      width: 20px;
      height: 20px;
      margin: 5px;
      cursor: pointer;

    }
  }

  // .layer_content {}

  .layer_line {
    position: absolute;
    top: 0;
    left: 0;
    width: 2px;
    height: 60%;
    // background-color: rgba(215, 14, 14, 0.7);
    // transform-origin: -61px 114px;
    transform-origin: -50px 20px;
    transform: rotate(40deg);
    // 灰色虚线
    background-image: repeating-linear-gradient(0deg, transparent, transparent 5px, rgb(39, 208, 216) 5px, rgb(39, 208, 216) 10px);
  }

  .layer_point {
    position: absolute;
    top: 0;
    left: 0;
    width: 10px;
    height: 10px;
    background-color: #ff1c0c;
    border-radius: 50%;
    // transform: translate(-50%, -50%);
    // transform-origin: -50px 20px;
    transform: translate(-32px, 67px);
    // 波动效果
    animation: wave 1s linear infinite;
  }

  @keyframes wave {
    0% {
      box-shadow: 0 0 0 0 rgba(255, 28, 12, 0.4);
    }

    50% {
      box-shadow: 0 0 0 20px rgba(255, 28, 12, 0);
    }

    100% {
      box-shadow: 0 0 0 0 rgba(255, 28, 12, 0);
    }
  }

  // .td_txt{
  //   // 文字的黑色阴影效果
  //   // text-shadow: 0 0 10px #000; // 水平偏移，垂直偏移，模糊半径，阴影颜色
  // }
}
</style>